package cn.kgc.vue.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.kgc.vue.common.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/8/8
 * @Description:
 * url :     http://192.168.1.32:8888/user/list
 * vue-cli   http://192.168.2.33:8080
 * 跨域：  http://192.168.2.33:8080    ->  http://192.168.1.32:8888/kgc/captcha
 *  协议+IP+port
 */

@RestController
@RequestMapping("captcha")
//@CrossOrigin   //  当前接口允许跨域访问
public class CaptchaController {

    @Autowired
    private StringRedisTemplate  stringRedisTemplate;

    @GetMapping
    public ResponseResult getCaptcha(){
        // sessionId  redis   uuid:code
        ResponseResult responseResult = new ResponseResult();

        LineCaptcha lineCaptcha = new LineCaptcha(110, 50, 4, 3);
        String code = lineCaptcha.getCode();
        // 将验证码图片转换成base64字符串
        String imageBase64 = lineCaptcha.getImageBase64();
        // 缓存在redis中 同时设置时效性  3min  uuid
        String uuid = IdUtil.simpleUUID();
        stringRedisTemplate.opsForValue().set(uuid,code,3, TimeUnit.MINUTES);

        HashMap<String, String> map = new HashMap<>();
        map.put("imguuid",uuid);
        map.put("img",imageBase64);
        responseResult.setCode(200);
        responseResult.setData(map);
        return responseResult;
    }
}
